package repository

import (
	"github.com/astaxie/beego/orm"
	"pq/models"
	"strings"
)

type SimuItemRespository struct{

}

func (sir SimuItemRespository) GetSimus(simuId string) ([]orm.Params,int){
	item := new(models.PqCsTestItem)
	items := item.ListSimuItems(simuId)
	for k,item := range items{
		s := strings.Split(item["section"].(string)," > ")
		if len(s) > 1 {
			items[k]["section"] = s[1]
		}else{
			items[k]["section"] = ""
		}
	}
	return items,len(items)
}

func (sir SimuItemRespository) ReOrder( simuLibId int) {
	slave := models.GetSlaveDb()
	var rows []models.PqCsSimuItemConnection
	_, _ = slave.QueryTable("pq_cs_simu_item_connection").Filter("pq_cs_test_simu_library_id",simuLibId).OrderBy("resource_id", "ordering").All(&rows)
	var od = 0
	master := models.GetMasterDb()
	for _,row := range rows {
		od++
		row.Ordering = od
		if row.ResourceId > 0 {
			_, _ = master.Update(&row)
		}
	}
}

func (sir SimuItemRespository) GetResource(resourceId int)(models.PqCsTestResource){
	slave := models.GetSlaveDb()
	resource := models.PqCsTestResource{Id:resourceId}
	slave.Read(&resource)
	return resource
}

func (sir SimuItemRespository) Collect(id int ,val int,uid string)(int64,error){
	master := models.GetMasterDb()
	var Connection models.PqCsSimuItemConnection
	_ = master.QueryTable("pq_cs_simu_item_connection").Filter("id", id).One(&Connection)
	Connection.IsCollected = val
	var Collection models.Collection
	Collection.PqCsTestItemId = Connection.PqCsTestItemId
	Collection.PqUserId = uid
	//master.QueryTable("collection").Filter("pq_user_id",uid).Filter("pq_cs_test_item_id",Connection.PqCsTestItemId).One(&Collection)
	//master.Read(&Collection{})
	_, _ = master.Insert(&Collection)
	return master.Update(&Connection)
}